package com.ikkong.school.controller;

import com.ikkong.core.base.BaseController;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.jfinal.ext.kit.JsonKit;
import com.ikkong.core.jfinal.ext.shiro.ShiroKit;
import com.ikkong.core.toolbox.Record;
import com.ikkong.school.model.Suppliers;
import com.ikkong.system.controller.base.UrlPermissController;
import com.ikkong.school.model.Product;
import com.ikkong.school.service.ProductService;
import com.ikkong.school.service.impl.ProductServiceImpl;

import java.util.Map;

/**
 * Generated by Blade.
 * 2018-07-09 22:32:44
 */
public class ProductController extends UrlPermissController {
	private static String CODE = "product";
	private static String PERFIX = "product";
	private static String LIST_SOURCE = "Product.list";
	private static String BASE_PATH = "/platform/product/";
	
	ProductService service = new ProductServiceImpl();
	
	public void index() {
		setAttr("code", CODE);
		render(BASE_PATH + "product.html");
	}

	public void add() {
        String string = ShiroKit.getUser().getDeptId().toString();
        Suppliers firstBy = Blade.create(Suppliers.class).findFirstBy("d_id = " + string, Suppliers.class);
       if(firstBy!=null){
           setAttr("dept",firstBy.getId());
           setAttr("deptname",firstBy.getName());
       }else {
           setAttr("dept",0);
       }
		setAttr("code", CODE);
		render(BASE_PATH + "product_add.html");
	}
	public void choose() {
		setAttr("code", CODE);
		render(BASE_PATH + "product_choose.html");
	}

	public void edit() {
		String id = getPara(0);
		Product product = service.findById(id);
		setAttr("model", JsonKit.toJson(product));
		setAttr("id", id);
		setAttr("code", CODE);
		render(BASE_PATH + "product_edit.html");
	}

	public void view() {
		String id = getPara(0);
		Product product = service.findById(id);
        Map map = Blade.dao().selectSingle("Product.view", Record.create().set("id", id), Map.class);
        setAttr("model", JsonKit.toJson(map));
        setAttr("map", map);
		setAttr("id", id);
		setAttr("code", CODE);
		render(BASE_PATH + "product_view.html");
	}

	public void list() {
		Object grid = paginate(LIST_SOURCE);
		renderJson(grid);
	}

	public void save() {
        Product product = getBean(Product.class);
		boolean temp = service.save(product);
		if (temp) {
			renderJson(success(SAVE_SUCCESS_MSG));
		} else {
			renderJson(error(SAVE_FAIL_MSG));
		}
	}

	public void update() {
		Product product = mapping(PERFIX, Product.class);
		product.setVersion(product.getVersion()+1);
		boolean temp = service.update(product);
		if (temp) {
			renderJson(success(UPDATE_SUCCESS_MSG));
		} else {
			renderJson(error(UPDATE_FAIL_MSG));
		}
	}

	public void remove() {
		String ids = getPara("ids");
		int cnt = service.deleteByIds(ids);
		if (cnt > 0) {
			renderJson(success(DEL_SUCCESS_MSG));
		} else {
			renderJson(error(DEL_FAIL_MSG));
		}
	}
}
